import { ref } from 'vue'
import { defineStore } from 'pinia'
import { login as loginApi,getUserInfo } from '@/api/auth'
import { getDynamicMenu } from '@/api/system'
import { ElMessage } from 'element-plus'
import { useMenuStore } from './menuModule'
import router from '@/router'

export const useUserStore = defineStore(
  'user',
  () => {
    const role = ref<string[]>([])

    const token = ref('')
    const setToken = (newToken: string) => {
      token.value = newToken
    }

    const expired = ref(0)
    const setExpired = (newExpired: number) => {
      expired.value = newExpired
    }

    const getExpired = () => {
      return expired.value
    }

    const getToken = () => {
      return token.value
    }

    const userInfo = ref({})
    const setUserInfo = (newUserInfo: object) => {
      userInfo.value = newUserInfo
    }

    const logout = () => {
      token.value = ''
      expired.value = 0
      userInfo.value = {}
      // 返回登录页面
      router.push('/login')
    }

    const login = async ({
      username,
      password,
    }: {
      username: string
      password: string
    }) => {
      const menuStore = useMenuStore()

      const res = await loginApi({ username, password })
      const {
        data: {
          data: { token, expired, role },
        },
      } = res
      setToken(token)
      setExpired(expired)
      role.value = role
      ElMessage({
        message: '登录成功',
        type: 'success',
      })

      router.push('/home')

      getDynamicMenu().then(res => {
        console.log('菜单', res)
        menuStore.setMenuList(res.data.data.menus)
      })
    }

    return {
      token,
      setToken,
      getToken,
      logout,
      getExpired,
      setExpired,
      expired,
      login,
      role,
    }
  },
  {
    persist: true,
  },
)
